const COLUMNS_PER_ROW = 5; // 每行显示3张图片
const Cc = Components.classes;
const Ci = Components.interfaces;
const Cu = Components.utils;
const XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
var apiUrl="";
var apiDomain="";
var uploadOk = 0;

function mainWindowOnLoad(){
	
	var minWidth = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService).getBranch(
                "extensions.imagepicker.").getIntPref("filter.minWidth");
    var minHeight = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService).getBranch(
                "extensions.imagepicker.").getIntPref("filter.minHeight");
	var minSize = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService).getBranch(
            "extensions.imagepicker.").getIntPref("filter.minSize");
//    alert(minWidth);            
	document.getElementById("minWidthTB").value = minWidth;
    document.getElementById("minHeightTB").value = minHeight;
    document.getElementById("minSizeTB").value = minSize;

	var strBundle = null;

	var bundleService = Components.classes["@mozilla.org/intl/stringbundle;1"].getService();
	bundleService = bundleService.QueryInterface(Components.interfaces.nsIStringBundleService);
	
	strBundle = bundleService.createBundle("chrome://picsave/locale/picsave.properties");

	apiUrl = strBundle.GetStringFromName("apiUrl");
	apiDomain = strBundle.GetStringFromName("apiDomain");
	
	//图片显示
	showImages();
	
	window.addEventListener("keyup",  function(e){// 点击关闭
		if(e.keyCode==27){// ESC键盘关闭
			close();
		}else if(e.keyCode==13){// Enter 键上传
			uploadAllSelected(document.getElementById("mainWindow-add-button"));
		}
	}, false);

	
}

function getImageSize(imageNode){
	var imageSrc = imageNode.src;
	
    //init cache session
    var cacheService = Cc["@mozilla.org/network/cache-service;1"].getService(Ci.nsICacheService);
    var httpCacheSession = cacheService.createSession("HTTP", Ci.nsICache.STORE_ANYWHERE, Ci.nsICache.STREAM_BASED);
    var url = imageSrc;
    var cacheKey = url.replace(/#.*$/, "");
    
    var fileSize = 0;
    try {
        // try to get from http cache, return nsICacheEntryDescriptor            
        var descriptor = httpCacheSession.openCacheEntry(cacheKey, Ci.nsICache.ACCESS_READ, false);
        if (descriptor) {
            fileSize = descriptor.dataSize;
            descriptor.close();
        }
    } catch (ex) {
        if (ex.result == 0x804B003D) {            
          
        } else if (ex.result == 0x804b0040) {
           
        } else {
        	
        }
        return 1024;
    }
    
    if (fileSize > 0) {
       return  fileSize;
    }else{
       return 1024;
    }        
		
}
function showImages() {	
	var params = window.arguments[0];
	var imageNodes = params.imageNodes;
	var imageContainer = document.getElementById("imagesContainer");

    // clean old image grid
    while (imageContainer.hasChildNodes()) {
        imageContainer.removeChild(imageContainer.firstChild);
    }
    // update filer from UI
    var minWidth = document.getElementById("minWidthTB").value;
    var minHeight = document.getElementById("minHeightTB").value;
    var minSize = document.getElementById("minSizeTB").value;
    Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService).getBranch(
                "extensions.imagepicker.").setIntPref("filter.minSize", minSize);
    Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService).getBranch(
                "extensions.imagepicker.").setIntPref("filter.minWidth", minWidth);
    Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService).getBranch(
                "extensions.imagepicker.").setIntPref("filter.minHeight", minHeight);
                
    var arr = [];
	for ( var i = 0, n = imageNodes.length; i < n; i++)
	{
        var fileSize = getImageSize(imageNodes[i]);
        fileSize = parseInt(fileSize/1024*100)/100;
//        alert(fileSize);
        if(fileSize<minSize||imageNodes[i].width<minWidth||imageNodes[i].height<minHeight){//文件过滤
        	continue;
        }
        imageNodes[i].fileSize = fileSize;
//        alert(imageNodes[i].src+"_"+fileSize+"_"+ imageNodes[i].fileSize);
		arr.push(imageNodes[i]);
	}
	displayImages(arr);
}

function displayImages(imageNodes){
	imageNodes = imageNodes || [];
	var arr = [];
	for ( var i = 0, n = imageNodes.length; i < n; i++)
	{

        var fileSize = getImageSize(imageNodes[i]);
        fileSize = parseInt(fileSize/1024*100)/100;
        if(fileSize<1||imageNodes[i].width<5||imageNodes[i].height<5){//文件过滤
        	continue;
        }
        imageNodes[i].fileSize = fileSize;
//        alert(imageNodes[i].src+"_"+fileSize+"_"+ imageNodes[i].fileSize);
		arr.push(imageNodes[i]);
	}
//	return;
	function ss(x,y){//排序
		if(x.width*x.height*x.fileSize>y.width*y.height*y.fileSize){
			return -1;
		}else{
			return 1;
		}
	}
	arr.sort(ss);	
	imageNodes = arr;
	document.getElementById("caption").setAttribute("label","图片列表:共有 "+imageNodes.length+" 张图片符合过滤条件")
	var cols = 0, row, image, hbox, checkbox;
	var rows = document.getElementById("imagesContainer");
	
	document.getElementById("selectAll").setAttribute("checked",true);
	for ( var i = 0, n = imageNodes.length; i < n; i++)
	{
		var imageNode = imageNodes[i];
		var imageSrc = imageNode.src;
//		if (imageSrc.toLowerCase().indexOf(".jpg")!=-1||imageSrc.toLowerCase().indexOf(".png")!=-1||imageSrc.toLowerCase().indexOf(".jpeg")!=-1||imageSrc.toLowerCase().indexOf(".gif")!=-1)
//		{
//			
//		}else{
//			continue;
//		}

		if (cols%COLUMNS_PER_ROW==0)
		{
			row = document.createElementNS(XUL_NS,"row"); // 开始新的一行
			row.setAttribute("align","center");			
			cols = 0;
		} 
		
		hbox = document.createElementNS(XUL_NS,"vbox");
		hbox.setAttribute("class", "image-cell");
		hbox.setAttribute("id", "image-cell"+i);
		hbox.setAttribute("align", "center");
		hbox.setAttribute("style","padding:5px 5px 5px 5px;");
		image = document.createElementNS(XUL_NS,"image");// 创建 XUL
		// 图像元素来显示图片
		image.setAttribute("src",imageSrc);			// 图像元素来显示图片
		
		var additionalLabel = document.createElementNS(XUL_NS, "label");
        additionalLabel.setAttribute("value", imageNode.width+"x"+imageNode.height+"    "+imageNode.fileSize+"KB");
		var base = 130;
        var w = imageNode.width;
        var h = imageNode.height;
        if(w>h){
            width = w>base?base:w;
        	height = width*h/w ;
        }else{
            height = h>base?base:h;
        	width = height*w/h;
        }
    	var mtop = parseInt((base-height)/2);
    	var mleft = parseInt((base-width)/2);
    		
		image.setAttribute("style","width:"+width+"px;height:"+height+"px;margin:"+mtop+"px "+mleft+"px;");			
		checkbox = document.createElementNS(XUL_NS,"checkbox");// 创建 XUL
																// 复选框元素以供用户选择
		checkbox.setAttribute("imageUrl",imageSrc);
		checkbox.setAttribute("label","选择");
		checkbox.setAttribute("checked",true);
		hbox.appendChild(image);
		hbox.appendChild(additionalLabel);
		hbox.appendChild(checkbox);
		row.appendChild(hbox);
		cols++;
		if ((cols %COLUMNS_PER_ROW==0&&cols!=0)||i==n-1)
		{
			rows.appendChild(row);
		}
		
	}
}
var saveDirectory = getDefaultSaveDirectory();
function selectSaveDirectory(){
	const	nsIFilePicker = Components.interfaces.nsIFilePicker;
	var fp = Components.classes["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker);
	fp.init(window,"",nsIFilePicker.modeGetFolder);
	var result = fp.show(); // 显示目录选择对话框
	if (result == nsIFilePicker.returnOK)
	{
		var file = fp.file;
		saveDirectory = file;
		document.getElementById("mainWindow-save-path").value = file.path;// 把目录的路径显示在文本框中
	}
}

// 获得默认的图片保存目录，也就是当前用户的根目录
function getDefaultSaveDirectory(){
	var file = Components.classes["@mozilla.org/file/directory_service;1"].getService(Components.interfaces.nsIProperties).get("Home",Components.interfaces.nsIFile);
	return file;
}
function downloadSingleImage(uri,callback){
	var ios = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService);
	var imageURI = ios.newURI(uri,null,null); // 创建图像的 URI
	var imageFileName = uri.substring(uri.lastIndexOf("/") + 1);
	var channel = ios.newChannelFromURI(imageURI); // 创建读取 URI 指定的数据流的通道
	var observer = {
		onStreamComplete : function(loader,context,status,length,result){
			var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
			file.initWithFile(saveDirectory); // 图片保存的目录
			file.appendRelativePath(imageFileName);
			var stream = Components.classes["@mozilla.org/network/safe-file-output-stream;1"].createInstance(Components.interfaces.nsIFileOutputStream);
			stream.init(file,-1,-1,0);
			var bstream = Components.classes["@mozilla.org/binaryoutputstream;1"].createInstance(Components.interfaces.nsIBinaryOutputStream);
			bstream.setOutputStream(stream);
			bstream.writeByteArray(result,length); // 把图片流的全部字节写入输出文件流中
			if (stream instanceof Components.interfaces.nsISafeOutputStream)
			{
				stream.finish();
			} else
			{
				stream.close();
			}
			if (typeof callback == "function")
			{
				callback();
			}
		}
	};
	var streamLoader = Components.classes["@mozilla.org/network/stream-loader;1"].createInstance(Components.interfaces.nsIStreamLoader);
	streamLoader.init(channel,observer,null);
}

function download(){
	var rows = document.getElementById("imagesContainer");
	var checkboxes = rows.getElementsByTagName("checkbox");
	var imageUrls = [];
	for ( var i = 0, n = checkboxes.length; i < n; i++)
	{
		if (checkboxes[i].checked)
		{
			imageUrls.push(checkboxes[i].getAttribute("imageUrl")); // 用户选择的图片的
																	// URL
		}
	}
	var progressmeter = document.getElementById("downloadProgress");
	progressmeter.style.visibility = "visible";
	var total = imageUrls.length, step = 100 / total, current = 0;
	for ( var i = 0; i < total; i++)
	{
		downloadSingleImage(imageUrls[i],function(){
			var value = parseInt(progressmeter.value); // 更新进度条
			progressmeter.value = value + step;
		});
	}
	close();
}

function uploadAllSelected(obj){
	obj.setAttribute("disabled",true);
	var rows = document.getElementById("imagesContainer");
	var checkboxes = rows.getElementsByTagName("checkbox");
	var imgArr = [];
	for ( var i = 0, n = checkboxes.length; i < n; i++)
	{
		if (checkboxes[i].checked)
		{
			imgArr.push(checkboxes[i].getAttribute("imageUrl")); // 用户选择的图片的
																	// URL
		}
	}
	var total = imgArr.length;
//	for ( var i = 0; i < total; i++)
//	{
//		uploadPicture(imgArr[i],i+1,total);
//	}

	var index = 0;	
	if(imgArr.length>0){		
		index++;
   		uploadPicture(imgArr.pop(),index,total);	// upload picture
	 }
    t = setInterval(function(){    	
   	 if(imgArr.length>0){
   		index++;
   		uploadPicture(imgArr.pop(),index,total);	// upload picture
   	 }else{
   		 clearInterval(t); 		
   	 }
   	
   },100);
}

function selectAll(){
	var rows = document.getElementById("imagesContainer");
	var checkboxes = rows.getElementsByTagName("checkbox");
	var selectAll = document.getElementById("selectAll").getAttribute("checked");

	for ( var i = 0, n = checkboxes.length; i < n; i++)
	{		
		checkboxes[i].setAttribute("checked",selectAll);		
	}
}
function uploadPicture(imgUrl,index,total) {
	var progressmeter = document.getElementById("downloadProgress");
	progressmeter.style.visibility = "visible";		
	
	var email;
	var password;
	var gallery_title;
	var sfw;
	var referer;

	var prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);


	if (prefs.getPrefType("extensions.picsave.prefs.email") == prefs.PREF_STRING) {
		email = prefs.getCharPref("extensions.picsave.prefs.email");
	};

	if (email!='') {

		var PMhostname = 'chrome://picsave';
		var PMformSubmitURL = 'Account Info';
		var password = '';

		try {

			if ("@mozilla.org/passwordmanager;1" in Components.classes) {

				try {

					var passwordManager = Components.classes["@mozilla.org/passwordmanager;1"].getService(Components.interfaces.nsIPasswordManager);

					var e = passwordManager.enumerator;

					while (e.hasMoreElements()) {

						try {
						
							var pass = e.getNext().QueryInterface(Components.interfaces.nsIPassword);
							if (pass.host == PMhostname && pass.user == email) {

								password = pass.password;
								break;

							};
							
						} catch (ex) { };

					};


				} catch(ex) { };

			} else if ("@mozilla.org/login-manager;1" in Components.classes) {

				var passwordManager = Components.classes["@mozilla.org/login-manager;1"].getService(Components.interfaces.nsILoginManager);
				var logins = passwordManager.findLogins({}, PMhostname, PMformSubmitURL, null);
  
				for (var i = 0; i < logins.length; i++) {

					if (logins[i].username == email) {

						password = logins[i].password;
						break;

					};

				};

			};

		} catch(ex) { };

	};
	var passwordmd5 = "";
	if (password!='') {

		var str = 'sess_picsave_'+password+'y';
		var converter = Components.classes["@mozilla.org/intl/scriptableunicodeconverter"].createInstance(Components.interfaces.nsIScriptableUnicodeConverter);

		converter.charset = "UTF-8";  
		var result = {};  
		var data = converter.convertToByteArray(str, result);
		var ch = Components.classes["@mozilla.org/security/hash;1"].createInstance(Components.interfaces.nsICryptoHash);
		ch.init(ch.MD5);  
		ch.update(data, data.length);  
		var hash = ch.finish(false);  

		function toHexString(charCode) {
			return ("0" + charCode.toString(16)).slice(-2);
		};

		function ahex(i) {

			if (!isNaN(i)) {

				return toHexString(hash.charCodeAt(i))
				
			};
			
		};

		passwordmd5 = [ahex(i) for (i in hash)].join("");

	};

	if (prefs.getPrefType("extensions.picsave.prefs.gallery_title") == prefs.PREF_STRING) {
		gallery_title = prefs.getCharPref("extensions.picsave.prefs.gallery_title");
	};

	if (prefs.getPrefType("extensions.picsave.prefs.sfw") == prefs.PREF_INT) {
		sfw = prefs.getIntPref("extensions.picsave.prefs.sfw");
	};

	var params = window.arguments[0];
	var pWin = params.pWin;
	referer = pWin.content.document.location;

	var url = escape(imgUrl);
	var newurl = apiUrl+'?f=upload&url='+url;
	

	newurl += '&e='+email+'&p='+passwordmd5;
	
	newurl +='&sfw='+sfw+'&st=1&ugt='+gallery_title+'&r='+escape(referer);
	
	
	var req = new XMLHttpRequest();
	req.open('GET', newurl, true);
	req.onreadystatechange = function(){ 

		if ( req.readyState == 4 ) {

			if ( req.status == 200 ) {
				uploadOk++;
				result = req.responseText;	
				result = eval("("+result+")");

				if (result.status==1) {								
					var value = parseInt(uploadOk*100/total); // 更新进度条
					progressmeter.value = value>100?100:value ;
					document.getElementById("mainWindow-add-button").setAttribute("label","Uploading ("+uploadOk+"/"+total+")");
					
				} else {

					alert(result.err);

				};				
				if(uploadOk==total){
					uploadOk = 0;
					setTimeout(function(){
						close();							
//						document.getElementById("mainWindow-add-button").setAttribute("label","ReUpload")
//						document.getElementById("mainWindow-add-button").setAttribute("disabled",false)
					},800);
					
				}
			} else {

				alert('There was a problem with the request\nstatus=' + req.status);

			};

		};			

	};
	req.send(null);			
	

};